package com.gla.giliair.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gla.giliair.dao.CustomerDao;
import com.gla.giliair.entity.*;
import com.gla.giliair.service.UserService;
import com.gla.giliair.util.BeanUtil;
import com.gla.giliair.util.IndentityUtil;
import com.gla.giliair.util.MapGenerator;
import com.gla.giliair.util.PatternUtil;
import com.gla.giliair.web.vo.Cus;
import com.gla.giliair.web.vo.CustomerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: Yingtian qian
 * @Date: 2021/8/23 16:06
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private CustomerDao customerDao;

    @Override
    public Customer selectCustomerById(Long customerId) {
        if (customerId != null) {
            CustomerExample customerExample = new CustomerExample();
            customerExample.or().andCustomerIdEqualTo(customerId);
            List<Customer> customerList = customerDao.selectByExample(customerExample);
            if (customerList.isEmpty()) {
                return null;
            }
            return customerList.get(0);
        }
        return null;
    }

    @Override
    public List<Customer> selectAllCustomers(CustomerExample orderBy) {
        List<Customer> customerList = customerDao.selectByExample(orderBy);
        return customerList;
    }

    @Override
    public List<Customer> selectCustomersByParams(CustomerExample orderBy, CustomerVO searchParams) {
        CustomerExample.Criteria criteria = orderBy.createCriteria();
        if (StringUtils.hasText(searchParams.getRealname())) {
            criteria.andRealnameLike("%" + searchParams.getRealname() + "%");
        }
        if (StringUtils.hasText(searchParams.getUsername())) {
            criteria.andUsernameLike("%" + searchParams.getUsername() + "%");
        }
        if (StringUtils.hasText(searchParams.getPhone())) {
            criteria.andPhoneLike("%" + searchParams.getPhone() + "%");
        }
        if (StringUtils.hasText(searchParams.getEmail())) {
            criteria.andEmailLike("%" + searchParams.getEmail() + "%");
        }
        if (StringUtils.hasText(searchParams.getIdNumber())) {
            criteria.andIdNumberLike("%" + searchParams.getIdNumber() + "%");
        }
        if (searchParams.getCustomerType() != null) {
            criteria.andCustomerTypeEqualTo(searchParams.getCustomerType());
        }
        List<Customer> customerList = customerDao.selectByExample(orderBy);
        return customerList;
    }

    @Override
    public Map<String, Object> registerUser(Customer user) {
        CustomerExample customerExample = new CustomerExample();
        customerExample.or().andUsernameEqualTo(user.getUsername());
        List<Customer> customerList = customerDao.selectByExample(customerExample);
        if (!customerList.isEmpty()) {
            return MapGenerator.getRes(509, "用户名已被注册！");
        }

        if (StringUtils.hasText(user.getPhone())) {
            CustomerExample customerExample2 = new CustomerExample();
            customerExample2.or().andPhoneEqualTo(user.getPhone());
            List<Customer> customerList2 = customerDao.selectByExample(customerExample2);
            if (!customerList2.isEmpty()) {
                return MapGenerator.getRes(510, "手机号已被注册！");
            }
        } else {
            CustomerExample customerExample2 = new CustomerExample();
            customerExample2.or().andEmailEqualTo(user.getEmail());
            List<Customer> customerList2 = customerDao.selectByExample(customerExample2);
            if (!customerList2.isEmpty()) {
                return MapGenerator.getRes(511, "邮箱已被注册！");
            }
        }

        Date nowDate = new Date();
        user.setCreateTime(nowDate);
        user.setUpdateTime(nowDate);

        if (customerDao.insertSelective(user) > 0) {
            return MapGenerator.getRes(200, "注册成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> checkLogin(String username, String password, HttpSession httpSession) {
        CustomerExample customerExample = new CustomerExample();
        customerExample.or().andUsernameEqualTo(username).andPasswordEqualTo(password);
        List<Customer> customerList = customerDao.selectByExample(customerExample);

        if (!customerList.isEmpty() && httpSession != null) {
            Customer user = customerList.get(0);
            if (user.getIsLocked() == 1) {
                return MapGenerator.getRes(502, "该用户已被封禁！");
            }
            CustomerVO userVO = new CustomerVO();
            BeanUtil.copyOne(user, userVO);
            httpSession.setAttribute("user", userVO);

            System.out.println("登录用户:" + httpSession);
            return MapGenerator.getResWithData(200, "登录成功！", userVO);
        }
        return MapGenerator.getRes(500, "用户名或密码错误！");
    }

    @Override
    public Map<String, Object> resetUserPassword(Customer user) {
        //检查用户是否存在
        CustomerExample customerExample = new CustomerExample();
        if (StringUtils.hasText(user.getPhone())) {
            customerExample.or().andPhoneEqualTo(user.getPhone());
        } else {
            customerExample.or().andEmailEqualTo(user.getEmail());
        }
        List<Customer> customerList = customerDao.selectByExample(customerExample);
        if (customerList.isEmpty()) {
            return MapGenerator.getRes(504, "用户不存在！");
        }

        Customer userFromDB = customerList.get(0);
        if (userFromDB.getIsLocked() == 1) {
            return MapGenerator.getRes(505, "该用户已被封禁！");
        }

        userFromDB.setPassword(user.getPassword());

        if (customerDao.updateByExampleSelective(userFromDB, customerExample) > 0) {
            return MapGenerator.getRes(200, "修改密码成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public CustomerVO updateUserInfo(CustomerVO userVO, HttpSession httpSession) {
        //前端输入的userVO，有效信息只包括：昵称、性别、身份证号、真名、生日、电话、邮箱；身份证和id要同时修改
        //从session中拿的userVO，只要其中的userId（必须登录后才能拿）
        CustomerVO userTemp = (CustomerVO) httpSession.getAttribute("user");
        //用userId从数据库里拿userEntity
        Customer userFromDB = selectCustomerById(userTemp.getCustomerId());
        //如果查到对应的userEntity
        if (userFromDB != null) {
            //用前端输入的userVO修改userEntity
            if (StringUtils.hasText(userVO.getNickname())) {
                userFromDB.setBirthday(userVO.getBirthday());
            }
            Integer gender = userVO.getGender();
            //防止gender为空出现异常
            if (new Integer(0).equals(gender) || new Integer(1).equals(gender) || new Integer(2).equals(gender)) {
                userFromDB.setGender(userVO.getGender());
            }
            if (StringUtils.hasText(userVO.getIdNumber()) && StringUtils.hasText(userVO.getRealname())) {
                try {
                    if (IndentityUtil.idCheck(userVO.getIdNumber(), userVO.getRealname())) {
                        userFromDB.setIdNumber(userVO.getIdNumber());
                        userFromDB.setRealname(userVO.getRealname());
                    } else {
                        //身份证不合法，更新失败
                        return null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (userVO.getBirthday() != null) {
                userFromDB.setRealname(userVO.getRealname());
            }

            if (StringUtils.hasText(userVO.getPhone())) {
                CustomerExample customerExample = new CustomerExample();
                customerExample.or().andPhoneEqualTo(userVO.getPhone());
                List<Customer> customerList = customerDao.selectByExample(customerExample);
                if (!customerList.isEmpty()) {
                    return null;
                }
                userFromDB.setPhone(userVO.getPhone());
            }
            if (StringUtils.hasText(userVO.getEmail())) {
                CustomerExample customerExample = new CustomerExample();
                customerExample.or().andEmailEqualTo(userVO.getEmail());
                List<Customer> customerList = customerDao.selectByExample(customerExample);
                if (!customerList.isEmpty()) {
                    return null;
                }
                userFromDB.setEmail(userVO.getEmail());
            }
            // 用userEntity更新用户
            if (customerDao.updateByPrimaryKeySelective(userFromDB) > 0) {
                //如果更新成功，重新拿userEntity，根据其更新session中的userVO
                CustomerVO userVORes = new CustomerVO();
                userFromDB = customerDao.selectByPrimaryKey(userFromDB.getCustomerId());
                BeanUtil.copyOne(userFromDB, userVORes);
                httpSession.setAttribute("user", userVORes);
                return userVORes;
            }
        }
        //更新失败
        return null;
    }

    @Override
    public Boolean isIdentityExist(String identity, Long userId) {
        //用userId从数据库里拿userEntity
        Customer userFromDB = selectCustomerById(userId);
        if (userFromDB != null) {
            if (PatternUtil.isEmail(identity)) {
                return userFromDB.getEmail().equals(identity);
            } else {
                return userFromDB.getPhone().equals(identity);
            }
        }
        return false;
    }

    @Override
    public Map<String, Object> findAllUsers(String sort, boolean isASC, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Customer> customerList = selectAllCustomers(customerSort(sort, isASC));
        PageInfo pageInfo = new PageInfo(customerList);
        if (!customerList.isEmpty()) {
            List<CustomerVO> customerVOList = BeanUtil.copyList(customerList, CustomerVO.class);
            pageInfo.setList(customerVOList);
            return MapGenerator.getResWithData(200, "查询用户列表成功！", pageInfo);
        } else {
            return MapGenerator.getRes(201, "查询结果为空！");
        }
    }

    @Override
    public Map<String, Object> addUser(Customer user) {

        CustomerExample customerExample = new CustomerExample();
        customerExample.or().andUsernameEqualTo(user.getUsername());
        List<Customer> customerList = customerDao.selectByExample(customerExample);
        if (!customerList.isEmpty()) {
            return MapGenerator.getRes(504, "用户名已被占用！");
        }

        if (StringUtils.hasText(user.getPhone())) {
            CustomerExample customerExample2 = new CustomerExample();
            customerExample2.or().andPhoneEqualTo(user.getPhone());
            List<Customer> customerList2 = customerDao.selectByExample(customerExample2);
            if (!customerList2.isEmpty()) {
                return MapGenerator.getRes(505, "手机号已被占用！");
            }
        }

        if (StringUtils.hasText(user.getEmail())) {
            CustomerExample customerExample2 = new CustomerExample();
            customerExample2.or().andEmailEqualTo(user.getEmail());
            List<Customer> customerList2 = customerDao.selectByExample(customerExample2);
            if (!customerList2.isEmpty()) {
                return MapGenerator.getRes(506, "邮箱已被占用！");
            }
        }

        Date nowDate = new Date();
        user.setCreateTime(nowDate);
        user.setUpdateTime(nowDate);

        if (customerDao.insertSelective(user) > 0) {
            return MapGenerator.getRes(200, "添加用户成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> modifyUser(Customer user) {
        Customer customerFromDB = selectCustomerById(user.getCustomerId());
        if (customerFromDB == null) {
            return MapGenerator.getRes(503, "用户不存在！");
        }

        if (StringUtils.hasText(user.getUsername())) {
            CustomerExample customerExample = new CustomerExample();
            customerExample.or().andUsernameEqualTo(user.getUsername());
            List<Customer> customerList = customerDao.selectByExample(customerExample);
            if (!customerList.isEmpty()) {
                return MapGenerator.getRes(504, "用户名已被占用，不能修改！");
            }
        }

        if (StringUtils.hasText(user.getPhone())) {
            CustomerExample customerExample = new CustomerExample();
            customerExample.or().andPhoneEqualTo(user.getPhone());
            List<Customer> customerList = customerDao.selectByExample(customerExample);
            if (!customerList.isEmpty()) {
                return MapGenerator.getRes(505, "手机号已被占用，不能修改！");
            }
        }

        if (StringUtils.hasText(user.getEmail())) {
            CustomerExample customerExample = new CustomerExample();
            customerExample.or().andEmailEqualTo(user.getEmail());
            List<Customer> customerList = customerDao.selectByExample(customerExample);
            if (!customerList.isEmpty()) {
                return MapGenerator.getRes(506, "邮箱已被占用，不能修改！");
            }
        }
        //把参数信息项中的非空字段合并到来自数据库的信息项中
        BeanUtil.copyOneIgnoreNull(user, customerFromDB);
        //覆盖更新日期
        customerFromDB.setUpdateTime(null);
        if (customerDao.updateByPrimaryKeySelective(customerFromDB) > 0) {
            return MapGenerator.getRes(200, "修改用户信息成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> searchCustomers(String sort, boolean isASC, Integer page, Integer pageSize, CustomerVO searchParams) {
        if (searchParams == null) {
            return MapGenerator.getRes(500, "搜索参数为空！");
        }
        PageHelper.startPage(page, pageSize);
        List<Customer> customerList = selectCustomersByParams(customerSort(sort, isASC), searchParams);
        PageInfo pageInfo = new PageInfo(customerList);
        if (!customerList.isEmpty()) {
            List<CustomerVO> customerVOList = BeanUtil.copyList(customerList, CustomerVO.class);
            pageInfo.setList(customerVOList);
            return MapGenerator.getResWithData(200, "查询用户列表成功！", pageInfo);
        } else {
            return MapGenerator.getRes(201, "查询结果为空！");
        }
    }

    //排序参数转化
    private CustomerExample customerSort(String sort, boolean isASC) {
        CustomerExample customerExample = new CustomerExample();
        sort = sort == null ? "" : sort;
        String column = "";
        String order = "desc";
        if (isASC) {
            order = "asc";
        }
        switch (sort) {
            case "customerId":
                column = "customer_id";
                break;
            case "username":
                column = "username";
                break;
            case "password":
                column = "password";
                break;
            case "nickname":
                column = "nickname";
                break;
            case "gender":
                column = "gender";
                break;
            case "phone":
                column = "phone";
                break;
            case "email":
                column = "email";
                break;
            case "customerType":
                column = "customerType";
                break;
            case "score":
                column = "score";
                break;
            case "IDNumber":
                column = "ID_number";
                break;
            case "realname":
                column = "realname";
                break;
            case "birthday":
                column = "birthday";
                break;
            case "createTime":
                column = "create_time";
                break;
            case "updateTime":
                column = "update_time";
                break;
            case "isLocked":
                column = "is_locked";
                break;
            default:
        }
        if ("".equals(column)) {
            customerExample.setOrderByClause("customer_id desc");
        } else {
            if ("customer_id".equals(column)) {
                customerExample.setOrderByClause(String.format("%s %s", column, order));
            } else {
                customerExample.setOrderByClause(String.format("%s %s , customer_id desc", column, order));
            }
        }
        return customerExample;
    }
}
